#!/bin/bash
# 去除可能存在的 Windows 行结束符
# zsh: ./install_xxx.sh: bad interpreter: /bin/bash^M: no such file or directory
# dos2unix install_zsh.sh

# 确保安装了 Zsh
if ! command -v zsh &> /dev/null; then
    echo "正在安装 Zsh..."
    sudo apt-get install -y zsh || sudo yum install -y zsh || brew install zsh
fi

# 确保安装了 tmux
if ! command -v tmux &> /dev/null; then
    echo "正在安装 tmux..."
    sudo apt-get install -y tmux || sudo yum install -y tmux || brew install tmux
fi

# 检查 tmux 版本是否符合要求
TMUX_VERSION=$(tmux -V | awk '{print $2}' | sed 's/[a-z]//g')
REQUIRED_VERSION=1.9

# 确保安装了 bc (用于版本比较)
if ! command -v bc &> /dev/null; then
    echo "正在安装 bc..."
    sudo apt-get install -y bc || sudo yum install -y bc || brew install bc
fi

if (( $(echo "$TMUX_VERSION < $REQUIRED_VERSION" | bc -l) )); then
    echo "警告: tmux 版本 ($TMUX_VERSION) 低于要求版本 ($REQUIRED_VERSION)"
    echo "请参考: https://github.com/tmux/tmux/wiki/Installing"
    echo "继续安装插件，但某些功能可能无法正常工作..."
fi

# 确保安装了 git 和 curl
if ! command -v git &> /dev/null; then
    echo "正在安装 Git..."
    sudo apt-get install -y git || sudo yum install -y git || brew install git
fi

if ! command -v curl &> /dev/null; then
    echo "正在安装 curl..."
    sudo apt-get install -y curl || sudo yum install -y curl || brew install curl
fi

# 检查并安装 Oh My Zsh
if [ ! -d "${HOME}/.oh-my-zsh" ]; then
    echo "正在安装 Oh My Zsh..."
    sh -c "$(curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)" "" --unattended
fi

# 设置 ZSH_CUSTOM 目录路径
ZSH_CUSTOM="${ZSH_CUSTOM:-${HOME}/.oh-my-zsh/custom}"

# 定义常用插件列表
plugins=(
    zsh-users/zsh-syntax-highlighting
    zsh-users/zsh-autosuggestions
    zsh-users/zsh-completions
)

# 安装 Zsh 插件
for plugin in "${plugins[@]}"; do
    plugin_name="${plugin##*/}"
    plugin_dir="${ZSH_CUSTOM}/plugins/${plugin_name}"
    if [ ! -d "$plugin_dir" ]; then
        echo "正在安装 Zsh 插件: ${plugin_name}"
        git clone "https://github.com/${plugin}.git" "$plugin_dir"
    fi
done

# 智能更新 .zshrc 配置文件
echo "正在更新 .zshrc 配置文件..."

# 备份原有的 .zshrc
if [ -f ~/.zshrc ]; then
    cp ~/.zshrc ~/.zshrc.backup
    echo "已备份原有 .zshrc 为 ~/.zshrc.backup"
fi

# 检查并更新 ZSH_THEME
if ! grep -q "^ZSH_THEME=" ~/.zshrc 2>/dev/null; then
    echo "ZSH_THEME=\"robbyrussell\"" >> ~/.zshrc
    echo "已添加 ZSH_THEME"
fi

# 检查并更新 plugins
if grep -q "^plugins=" ~/.zshrc 2>/dev/null; then
    # 如果 plugins 行已存在，添加缺失的插件
    for plugin in tmux zsh-syntax-highlighting zsh-autosuggestions zsh-completions; do
        if ! grep -q "plugins=.*$plugin" ~/.zshrc; then
            sed -i "s/^plugins=([^)]*/& $plugin/" ~/.zshrc
            echo "已添加插件: $plugin"
        fi
    done
else
    # 如果 plugins 行不存在，添加新的 plugins 行
    echo 'plugins=(git tmux zsh-syntax-highlighting zsh-autosuggestions zsh-completions)' >> ~/.zshrc
    echo "已添加 plugins 配置"
fi

# 确保 source 行存在
if ! grep -q "source.*oh-my-zsh.sh" ~/.zshrc; then
    echo 'source $ZSH/oh-my-zsh.sh' >> ~/.zshrc
    echo "已添加 source 行"
fi

# 安装 Tmux 插件管理器 (tpm)
TMUX_PLUGINS_DIR="${HOME}/.tmux/plugins"
if [ ! -d "${TMUX_PLUGINS_DIR}/tpm" ]; then
    echo "正在安装 Tmux 插件管理器 (tpm)..."
    mkdir -p "${TMUX_PLUGINS_DIR}"
    git clone https://github.com/tmux-plugins/tpm "${TMUX_PLUGINS_DIR}/tpm"
fi

# 智能更新 .tmux.conf 配置文件
echo "正在更新 .tmux.conf 配置文件..."
TMUX_CONF="${HOME}/.tmux.conf"

# 备份原有的 tmux 配置
if [ -f "$TMUX_CONF" ]; then
    cp "$TMUX_CONF" "${TMUX_CONF}.bak"
    echo "已备份原有 tmux 配置到 ${TMUX_CONF}.bak"
fi

# 创建临时文件来构建新的 tmux 配置
TEMP_TMUX_CONF=$(mktemp)

# 如果原文件存在，先复制内容
if [ -f "$TMUX_CONF" ]; then
    cat "$TMUX_CONF" > "$TEMP_TMUX_CONF"
else
    touch "$TEMP_TMUX_CONF"
fi

# 检查并更新 TPM 路径设置
if ! grep -q "TMUX_PLUGIN_MANAGER_PATH" "$TEMP_TMUX_CONF" 2>/dev/null; then
    echo "# 设置 TPM 路径" >> "$TEMP_TMUX_CONF"
    echo 'set-environment -g TMUX_PLUGIN_MANAGER_PATH "$HOME/.tmux/plugins"' >> "$TEMP_TMUX_CONF"
    echo "已添加 TPM 路径设置"
fi

# 检查并更新插件配置
TMUX_PLUGINS=('tmux-plugins/tpm' 'tmux-plugins/tmux-resurrect' 'tmux-plugins/tmux-continuum')

for plugin in "${TMUX_PLUGINS[@]}"; do
    if ! grep -q "@plugin.*$plugin" "$TEMP_TMUX_CONF" 2>/dev/null; then
        # 如果插件配置不存在，添加
        if ! grep -q "@plugin" "$TEMP_TMUX_CONF" 2>/dev/null; then
            echo "" >> "$TEMP_TMUX_CONF"
            echo "# Tmux 插件配置" >> "$TEMP_TMUX_CONF"
        fi
        echo "set -g @plugin '$plugin'" >> "$TEMP_TMUX_CONF"
        echo "已添加插件: $plugin"
    fi
done

# 检查并更新自动保存配置
AUTO_SAVE_SETTINGS=(
    "continuum-save-interval"
    "continuum-restore"
    "resurrect-capture-pane-contents"
)

for setting in "${AUTO_SAVE_SETTINGS[@]}"; do
    if ! grep -q "@$setting" "$TEMP_TMUX_CONF" 2>/dev/null; then
        # 如果设置不存在，添加
        if ! grep -q "@continuum-" "$TEMP_TMUX_CONF" 2>/dev/null && ! grep -q "@resurrect-" "$TEMP_TMUX_CONF" 2>/dev/null; then
            echo "" >> "$TEMP_TMUX_CONF"
            echo "# 自动保存配置" >> "$TEMP_TMUX_CONF"
        fi
        
        case "$setting" in
            "continuum-save-interval")
                echo "set -g @continuum-save-interval '1'" >> "$TEMP_TMUX_CONF"
                ;;
            "continuum-restore")
                echo "set -g @continuum-restore 'on'" >> "$TEMP_TMUX_CONF"
                ;;
            "resurrect-capture-pane-contents")
                echo "set -g @resurrect-capture-pane-contents 'on'" >> "$TEMP_TMUX_CONF"
                ;;
        esac
        echo "已添加设置: $setting"
    fi
done

# 检查并更新状态栏长度设置
if ! grep -q "status-left-length" "$TEMP_TMUX_CONF" 2>/dev/null; then
    echo "" >> "$TEMP_TMUX_CONF"
    echo "# 设置左侧状态栏长度" >> "$TEMP_TMUX_CONF"
    echo "set -g status-left-length 100" >> "$TEMP_TMUX_CONF"
    echo "已添加状态栏长度设置"
fi

# 检查并更新状态栏长度设置
if ! grep -q "bind s choose-tree -s -O name" "$TEMP_TMUX_CONF" 2>/dev/null; then
    echo "" >> "$TEMP_TMUX_CONF"
    echo "# 绑定 Ctrl+b + S 来展示按名称排序的会话列表" >> "$TEMP_TMUX_CONF"
    echo "bind s choose-tree -s -O name" >> "$TEMP_TMUX_CONF"
    echo "已添加绑定 Ctrl+b + S 来展示按名称排序的会话列表"
fi

# 检查并更新 TPM 初始化
if ! grep -q "run.*tpm/tpm" "$TEMP_TMUX_CONF" 2>/dev/null; then
    echo "" >> "$TEMP_TMUX_CONF"
    echo "# 初始化 TPM" >> "$TEMP_TMUX_CONF"
    echo 'run '\''$HOME/.tmux/plugins/tpm/tpm'\''' >> "$TEMP_TMUX_CONF"
    echo "已添加 TPM 初始化"
fi

# 将临时文件内容写回原文件
mv "$TEMP_TMUX_CONF" "$TMUX_CONF"

# 将 Zsh 设置为默认 shell
CURRENT_SHELL=$(basename "$SHELL")
if [ "$CURRENT_SHELL" != "zsh" ]; then
    echo "将 Zsh 设置为默认 shell..."
    chsh -s $(which zsh)
else
    echo "Zsh 已经是默认 shell"
fi

# 完成提示
echo "----------------------------"
echo "安装完成！"
echo ""
echo "重要提示："
echo "1. 请重新登录或重启终端以使用 Zsh"
echo "2. 启动新的 tmux 会话后，按 'prefix + I' (大写 I) 安装 tmux 插件"
echo ""
echo "Tmux 自动保存功能使用说明:"
echo "  - 手动保存: prefix + Ctrl-s   (prefix 通常是 Ctrl-b)"
echo "  - 恢复会话: prefix + Ctrl-r"
echo "  - 选择会话: prefix + s"
echo ""
echo "注意:"
echo "  - 原有的 .zshrc 已备份为 ~/.zshrc.backup"
echo "  - 原有的 .tmux.conf 已备份为 ~/.tmux.conf.bak"
echo "  - Tmux 自动保存功能会在后台每1分钟自动保存一次"
echo "  - 重启后进入 tmux 会自动恢复之前的会话"
echo "----------------------------"

# 如果当前在 tmux 会话中，提示重新加载配置
if [ -n "$TMUX" ]; then
    echo ""
    echo "检测到当前在 tmux 会话中，请运行以下命令重新加载配置:"
    echo "tmux source-file ~/.tmux.conf"
fi
